package com.ruoyi.business.service.impl;

import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.business.domain.Station;
import com.ruoyi.business.domain.vo.PlatformVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.PlatformMapper;
import com.ruoyi.business.domain.Platform;
import com.ruoyi.business.service.IPlatformService;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.ss.usermodel.IndexedColors;

/**
 * 车站管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-03-21
 */
@Service
public class PlatformServiceImpl implements IPlatformService
{
    @Autowired
    private PlatformMapper platformMapper;

    /**
     * 查询车站管理
     * 
     * @param id 车站管理主键
     * @return 车站管理
     */
    @Override
    public Platform selectPlatformById(Long id)
    {
        return platformMapper.selectPlatformById(id);
    }

    /**
     * 查询车站管理列表
     * 
     * @param platform 车站管理
     * @return 车站管理
     */
    @Override
    public List<Platform> selectPlatformList(Platform platform)
    {
        return platformMapper.selectPlatformList(platform);
    }

    /**
     * 新增车站管理
     * 
     * @param platform 车站管理
     * @return 结果
     */
    @Override
    public int insertPlatform(Platform platform)
    {
        return platformMapper.insertPlatform(platform);
    }

    /**
     * 修改车站管理
     * 
     * @param platform 车站管理
     * @return 结果
     */
    @Override
    public int updatePlatform(Platform platform)
    {
        return platformMapper.updatePlatform(platform);
    }

    /**
     * 批量删除车站管理
     * 
     * @param ids 需要删除的车站管理主键
     * @return 结果
     */
    @Override
    public int deletePlatformByIds(Long[] ids)
    {
        return platformMapper.deletePlatformByIds(ids);
    }

    /**
     * 删除车站管理信息
     * 
     * @param id 车站管理主键
     * @return 结果
     */
    @Override
    public int deletePlatformById(Long id)
    {
        return platformMapper.deletePlatformById(id);
    }


    /**
     * 批量新增车站管理
     * @param platformList 需要删除的数据主键集合
     * @return 结果
     */
    @Override
    public int insertPlatforms(List<Platform> platformList) {
        return platformMapper.insertPlatforms(platformList);
    }

    /**
     * 获取有车站的城市列表
     *
     * @param platform 查询条件
     * @return 城市列表
     */
    @Override
    public List<Platform> selectCitiesWithPlatforms(Platform platform) {
        return platformMapper.selectCitiesWithPlatforms(platform);
    }

    @Override
    public List<Platform> selectPlatformsByStationName(String stationName) {
        return platformMapper.selectPlatformsByStationName(stationName);
    }

    @Override
    public boolean existsPlatformByCityIdAndStationName(Long cityId, String stationName) {
        List<Platform> platforms = platformMapper.selectPlatformsByCityIdAndStationName(cityId, stationName);
        return platforms != null && !platforms.isEmpty();
    }

    /**
     * 下载车站管理导入模板 - 不包含错误字段
     */
    @Override
    public void downloadCustomTemplate(HttpServletResponse response) throws IOException {
        // 创建自定义的工作簿和工作表
        SXSSFWorkbook wb = new SXSSFWorkbook(500);
        try {
            Sheet sheet = wb.createSheet("车站管理数据");
            
            // 创建表头行并设置样式
            Row headerRow = sheet.createRow(0);
            CellStyle headerStyle = wb.createCellStyle();
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            headerStyle.setBorderBottom(BorderStyle.THIN);
            headerStyle.setBorderLeft(BorderStyle.THIN);
            headerStyle.setBorderRight(BorderStyle.THIN);
            headerStyle.setBorderTop(BorderStyle.THIN);
            headerStyle.setAlignment(HorizontalAlignment.CENTER);
            
            Font headerFont = wb.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            
            // 设置业务相关列，包含ID字段
            String[] headers = {"ID", "城市ID", "站点名", "站点名拼音", "站点名首字母", "车站类型"};
            for (int i = 0; i < headers.length; i++) {
                Cell headerCell = headerRow.createCell(i);
                headerCell.setCellValue(headers[i]);
                headerCell.setCellStyle(headerStyle);
                sheet.setColumnWidth(i, 5000); // 设置合适的列宽
            }
            
            // 创建数据行样式
            CellStyle dataStyle = wb.createCellStyle();
            dataStyle.setBorderBottom(BorderStyle.THIN);
            dataStyle.setBorderLeft(BorderStyle.THIN);
            dataStyle.setBorderRight(BorderStyle.THIN);
            dataStyle.setBorderTop(BorderStyle.THIN);
            
            // 添加示例数据
            Row exampleRow = sheet.createRow(1);
            
            // ID示例
            Cell cellId = exampleRow.createCell(0);
            cellId.setCellValue("1890636568357368001");
            cellId.setCellStyle(dataStyle);
            
            // 城市ID示例
            Cell cell0 = exampleRow.createCell(1);
            cell0.setCellValue("1890636568357368878");
            cell0.setCellStyle(dataStyle);
            
            // 站点名示例
            Cell cell1 = exampleRow.createCell(2);
            cell1.setCellValue("北京西站");
            cell1.setCellStyle(dataStyle);
            
            // 站点名拼音示例
            Cell cell2 = exampleRow.createCell(3);
            cell2.setCellValue("beijingxizhan");
            cell2.setCellStyle(dataStyle);
            
            // 站点名首字母示例
            Cell cell3 = exampleRow.createCell(4);
            cell3.setCellValue("bjxz");
            cell3.setCellStyle(dataStyle);
            
            // 车站类型示例
            Cell cell4 = exampleRow.createCell(5);
            cell4.setCellValue("1");
            cell4.setCellStyle(dataStyle);
            
            // 输出到响应
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = "platform_template.xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            
            wb.write(response.getOutputStream());
        } finally {
            wb.dispose();
        }
    }
    
    /**
     * 导出车站管理导入错误数据 - 使用ID替代行号
     */
    @Override
    public void exportCustomErrorData(HttpServletResponse response, List<PlatformVo> errorDataList) throws IOException {
        // 创建自定义的工作簿和工作表
        SXSSFWorkbook wb = new SXSSFWorkbook(500);
        try {
            // 先记录一下要导出的数据
            System.out.println("导出错误数据数量: " + (errorDataList != null ? errorDataList.size() : 0));
            if (errorDataList != null && !errorDataList.isEmpty()) {
                for (PlatformVo vo : errorDataList) {
                    System.out.println("导出的错误数据: id=" + vo.getId() 
                        + ", cityId=" + vo.getCityId() 
                        + ", stationName=" + vo.getStationName() 
                        + ", stationType=" + vo.getStationType()
                        + ", errorMsg=" + vo.getErrorMsg());
                }
            }
            
            Sheet sheet = wb.createSheet("车站管理错误数据");
            
            // 创建表头行并设置样式
            Row headerRow = sheet.createRow(0);
            CellStyle headerStyle = wb.createCellStyle();
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            headerStyle.setBorderBottom(BorderStyle.THIN);
            headerStyle.setBorderLeft(BorderStyle.THIN);
            headerStyle.setBorderRight(BorderStyle.THIN);
            headerStyle.setBorderTop(BorderStyle.THIN);
            headerStyle.setAlignment(HorizontalAlignment.CENTER);
            
            Font headerFont = wb.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            
            // 设置列，包含ID而不是行号
            String[] headers = {"ID", "城市ID", "站点名", "站点名拼音", "站点名首字母", "车站类型", "错误原因"};
            for (int i = 0; i < headers.length; i++) {
                Cell headerCell = headerRow.createCell(i);
                headerCell.setCellValue(headers[i]);
                headerCell.setCellStyle(headerStyle);
                sheet.setColumnWidth(i, 6000); // 设置合适的列宽
            }
            
            // 创建数据行样式
            CellStyle dataStyle = wb.createCellStyle();
            dataStyle.setBorderBottom(BorderStyle.THIN);
            dataStyle.setBorderLeft(BorderStyle.THIN);
            dataStyle.setBorderRight(BorderStyle.THIN);
            dataStyle.setBorderTop(BorderStyle.THIN);
            
            // 错误信息样式（红色文字）
            CellStyle errorStyle = wb.createCellStyle();
            errorStyle.cloneStyleFrom(dataStyle);
            Font errorFont = wb.createFont();
            errorFont.setColor(IndexedColors.RED.getIndex());
            errorStyle.setFont(errorFont);
            
            // 如果没有数据，添加一条提示
            if (errorDataList == null || errorDataList.isEmpty()) {
                Row dataRow = sheet.createRow(1);
                Cell cell = dataRow.createCell(0);
                cell.setCellValue("没有错误数据");
                cell.setCellStyle(dataStyle);
                sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 6));
            } else {
                // 填充数据行
                int rowIndex = 1;
                for (PlatformVo vo : errorDataList) {
                    Row dataRow = sheet.createRow(rowIndex++);
                    
                    try {
                        // ID列
                        Cell cell0 = dataRow.createCell(0);
                        String idValue = vo.getId() != null ? vo.getId().toString() : "";
                        cell0.setCellValue(idValue);
                        cell0.setCellStyle(dataStyle);
                        
                        // 城市ID
                        Cell cell1 = dataRow.createCell(1);
                        String cityIdValue = vo.getCityId() != null ? vo.getCityId().toString() : "";
                        cell1.setCellValue(cityIdValue);
                        cell1.setCellStyle(dataStyle);
                        
                        // 站点名
                        Cell cell2 = dataRow.createCell(2);
                        cell2.setCellValue(vo.getStationName() != null ? vo.getStationName() : "");
                        cell2.setCellStyle(dataStyle);
                        
                        // 站点名拼音
                        Cell cell3 = dataRow.createCell(3);
                        cell3.setCellValue(vo.getStationPinyin() != null ? vo.getStationPinyin() : "");
                        cell3.setCellStyle(dataStyle);
                        
                        // 站点名首字母
                        Cell cell4 = dataRow.createCell(4);
                        cell4.setCellValue(vo.getStationInitials() != null ? vo.getStationInitials() : "");
                        cell4.setCellStyle(dataStyle);
                        
                        // 车站类型
                        Cell cell5 = dataRow.createCell(5);
                        cell5.setCellValue(vo.getStationType() != null ? vo.getStationType() : "");
                        cell5.setCellStyle(dataStyle);
                        
                        // 错误原因
                        Cell cell6 = dataRow.createCell(6);
                        cell6.setCellValue(vo.getErrorMsg() != null ? vo.getErrorMsg() : "");
                        cell6.setCellStyle(errorStyle); // 使用错误样式
                    } catch (Exception e) {
                        System.err.println("处理行数据异常: " + e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
            
            // 输出到响应
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = "platform_error_data_" + System.currentTimeMillis() + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            
            wb.write(response.getOutputStream());
        } catch (Exception e) {
            System.err.println("导出Excel异常: " + e.getMessage());
            e.printStackTrace();
            throw new IOException("导出Excel失败", e);
        } finally {
            wb.dispose();
        }
    }

    /**
     * 清空车站数据
     * 
     * @return 结果
     */
    @Override
    public int clearPlatform() {
        return platformMapper.clearPlatform();
    }

}
